package com.itkf.core.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itkf.core.configCenter.ConfigCenterService;
import com.itkf.core.configCenter.example.NacosConfigCenterService;
import com.itkf.core.configCenter.example.RedisConfigCenterService;
import com.itkf.core.lifecycle.DtpRegistry;
import com.itkf.core.listener.DtpConfigChangeListener;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(DtpProperties.class)
public class DtpAutoConfig {
    @Bean
    @ConditionalOnMissingBean
    public DtpRegistry dtpRegistry(DtpProperties dtpProperties) {
        return new DtpRegistry(dtpProperties);
    }

    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper();
    }

    @Bean
    @ConditionalOnMissingBean
    public ConfigCenterService configCenterService(DtpProperties dtpProperties) {
        return switch (dtpProperties.getConfigType().toLowerCase()) {
            case "nacos" -> new NacosConfigCenterService(dtpProperties);
            case "redis" -> new RedisConfigCenterService(dtpProperties);
            default -> throw new IllegalStateException("Unsupported config center type");
        };
    }

    @Bean
    public DtpConfigChangeListener dtpConfigChangeListener(
            DtpRegistry dtpRegistry,
            DtpProperties dtpProperties,
            ObjectMapper objectMapper) {
        return new DtpConfigChangeListener(objectMapper, dtpProperties, dtpRegistry);
    }

    @Bean
    public ApplicationRunner configCenterSubscriber(
            ConfigCenterService configCenterService,
            DtpConfigChangeListener listener) {
        return args -> {
            configCenterService.init();
            configCenterService.subscribe(listener);
        };
    }
}
